<!doctype html>




<html class="theme-next pisces" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
    
  
  <link href="//cdn.jsdelivr.net/fancybox/2.1.5/jquery.fancybox.min.css" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic|Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






  

<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="linux,shell,bash," />





  <link rel="alternate" href="/atom.xml" title="不知归期的故人" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/images/favicon.ico?v=5.1.0" />






<meta name="description" content="Shell 快速指南12345███████╗██╗  ██╗███████╗██╗     ██╗                           ██╔════╝██║  ██║██╔════╝██║     ██║                           ███████╗███████║█████╗  ██║     ██║">
<meta name="keywords" content="linux,shell,bash">
<meta property="og:type" content="article">
<meta property="og:title" content="Shell 快速指南">
<meta property="og:url" content="https://kusole.github.io/2017/12/04/shell/index.html">
<meta property="og:site_name" content="不知归期的故人">
<meta property="og:description" content="Shell 快速指南12345███████╗██╗  ██╗███████╗██╗     ██╗                           ██╔════╝██║  ██║██╔════╝██║     ██║                           ███████╗███████║█████╗  ██║     ██║">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2018-10-13T14:39:56.282Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Shell 快速指南">
<meta name="twitter:description" content="Shell 快速指南12345███████╗██╗  ██╗███████╗██╗     ██╗                           ██╔════╝██║  ██║██╔════╝██║     ██║                           ███████╗███████║█████╗  ██║     ██║">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: false,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://kusole.github.io/2017/12/04/shell/"/>





  <title> Shell 快速指南 | 不知归期的故人 </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?124e5902fa6b3c1d89682ed1fa0441ac";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>










  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">不知归期的故人</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">乘风破浪会有时，直挂云帆济沧海。</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocapitalize="off" autocomplete="off" autocorrect="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="https://kusole.github.io/2017/12/04/shell/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="刘韬">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/uploads/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="不知归期的故人">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                Shell 快速指南
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-12-04T08:54:45+08:00">
                2017-12-04
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/linux/" itemprop="url" rel="index">
                    <span itemprop="name">linux</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="Shell-快速指南"><a href="#Shell-快速指南" class="headerlink" title="Shell 快速指南"></a>Shell 快速指南</h1><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">███████╗██╗  ██╗███████╗██╗     ██╗                           </span><br><span class="line">██╔════╝██║  ██║██╔════╝██║     ██║                           </span><br><span class="line">███████╗███████║█████╗  ██║     ██║                           </span><br><span class="line">╚════██║██╔══██║██╔══╝  ██║     ██║                           </span><br><span class="line">███████║██║  ██║███████╗███████╗███████╗</span><br></pre></td></tr></table></figure>
<a id="more"></a>
<h2 id="概述"><a href="#概述" class="headerlink" title="概述"></a>概述</h2><h3 id="什么是-shell"><a href="#什么是-shell" class="headerlink" title="什么是 shell"></a>什么是 shell</h3><p>Shell 是一个用 C 语言编写的程序，它是用户使用 Linux 的桥梁。</p>
<p>Shell 既是一种命令语言，又是一种程序设计语言。</p>
<p>Shell 是指一种应用程序，这个应用程序提供了一个界面，用户通过这个界面访问 Linux 内核的服务。</p>
<p>Ken Thompson 的 sh 是第一种 Unix Shell，Windows Explorer 是一个典型的图形界面 Shell。</p>
<h3 id="什么是-shell-脚本"><a href="#什么是-shell-脚本" class="headerlink" title="什么是 shell 脚本"></a>什么是 shell 脚本</h3><p>Shell 脚本（shell script），是一种为 shell 编写的脚本程序，一般文件后缀为 <code>.sh</code>。</p>
<p>业界所说的 shell 通常都是指 shell 脚本，但 shell 和 shell script 是两个不同的概念。</p>
<h3 id="Shell-环境"><a href="#Shell-环境" class="headerlink" title="Shell 环境"></a>Shell 环境</h3><p>Shell 编程跟 java、php 编程一样，只要有一个能编写代码的文本编辑器和一个能解释执行的脚本解释器就可以了。</p>
<p>Shell 的解释器种类众多，常见的有：</p>
<ul>
<li><a href="https://www.gnu.org/software/bash/" target="_blank" rel="noopener">sh</a> - 即 Bourne Shell。sh 是 Unix 标准默认的 shell。</li>
<li><a href="https://www.gnu.org/software/bash/" target="_blank" rel="noopener">bash</a> - 即 Bourne Again Shell。bash 是 Linux 标准默认的 shell。</li>
<li><a href="https://fishshell.com/" target="_blank" rel="noopener">fish</a> - 智能和用户友好的命令行 shell。</li>
<li><a href="http://xiki.org/" target="_blank" rel="noopener">xiki</a> - 使 shell 控制台更友好，更强大。</li>
<li><a href="http://www.zsh.org/" target="_blank" rel="noopener">zsh</a> - 功能强大的 shell 与脚本语言。</li>
</ul>
<h4 id="指定脚本解释器"><a href="#指定脚本解释器" class="headerlink" title="指定脚本解释器"></a>指定脚本解释器</h4><p>在 shell 脚本，<code>#!</code> 告诉系统其后路径所指定的程序即是解释此脚本文件的 Shell 解释器。<code>#!</code> 被称作<a href="https://zh.wikipedia.org/wiki/Shebang" target="_blank" rel="noopener">shebang（也称为 Hashbang ）</a>。</p>
<p>所以，你应该会在 shell 中，见到诸如以下的注释：</p>
<ul>
<li>指定 sh 解释器</li>
</ul>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#!/bin/sh</span></span><br></pre></td></tr></table></figure>
<ul>
<li>指定 bash 解释器</li>
</ul>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#!/bin/bash</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p><strong>注意</strong></p>
<p>上面的指定解释器的方式是比较常见的，但有时候，你可能也会看到下面的方式：</p>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&gt; <span class="comment">#!/usr/bin/env bash</span></span><br><span class="line">&gt;</span><br></pre></td></tr></table></figure>
</blockquote>
<blockquote>
<p>这样做的好处是，系统会自动在 <code>PATH</code> 环境变量中查找你指定的程序（本例中的<code>bash</code>）。相比第一种写法，你应该尽量用这种写法，因为程序的路径是不确定的。这样写还有一个好处，操作系统的<code>PATH</code>变量有可能被配置为指向程序的另一个版本。比如，安装完新版本的<code>bash</code>，我们可能将其路径添加到<code>PATH</code>中，来“隐藏”老版本。如果直接用<code>#!/bin/bash</code>，那么系统会选择老版本的<code>bash</code>来执行脚本，如果用<code>#!/usr/bin/env bash</code>，则会使用新版本。</p>
</blockquote>
<h3 id="模式"><a href="#模式" class="headerlink" title="模式"></a>模式</h3><p>shell 有交互和非交互两种模式。</p>
<h4 id="交互模式"><a href="#交互模式" class="headerlink" title="交互模式"></a>交互模式</h4><blockquote>
<p>简单来说，你可以将 shell 的交互模式理解为执行命令行。</p>
</blockquote>
<p>看到形如下面的东西，说明shell处于交互模式下：</p>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">user@host:~$</span><br></pre></td></tr></table></figure>
<p>接着，便可以输入一系列 Linux 命令，比如 <code>ls</code>，<code>grep</code>，<code>cd</code>，<code>mkdir</code>，<code>rm</code> 等等。</p>
<h4 id="非交互模式"><a href="#非交互模式" class="headerlink" title="非交互模式"></a>非交互模式</h4><blockquote>
<p>简单来说，你可以将 shell 的非交互模式理解为执行 shell 脚本。</p>
</blockquote>
<p>在非交互模式下，shell 从文件或者管道中读取命令并执行。</p>
<p>当 shell 解释器执行完文件中的最后一个命令，shell 进程终止，并回到父进程。</p>
<p>可以使用下面的命令让shell以非交互模式运行：</p>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">sh /path/to/script.sh</span><br><span class="line">bash /path/to/script.sh</span><br></pre></td></tr></table></figure>
<p>上面的例子中，<code>script.sh</code>是一个包含shell解释器可以识别并执行的命令的普通文本文件，<code>sh</code>和<code>bash</code>是shell解释器程序。你可以使用任何喜欢的编辑器创建<code>script.sh</code>（vim，nano，Sublime Text, Atom等等）。</p>
<p>除此之外，你还可以通过<code>chmod</code>命令给文件添加可执行的权限，来直接执行脚本文件：</p>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">chmod +x /path/to/script.sh <span class="comment">#使脚本具有执行权限</span></span><br><span class="line">/path/to/test.sh</span><br></pre></td></tr></table></figure>
<p>这种方式要求脚本文件的第一行必须指明运行该脚本的程序，比如：</p>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#!/bin/bash</span></span><br><span class="line"><span class="built_in">echo</span> <span class="string">"Hello, world!"</span></span><br></pre></td></tr></table></figure>
<p>上面的例子中，我们使用了一个很有用的命令<code>echo</code>来输出字符串到屏幕上。</p>
<h2 id="Shell-编程"><a href="#Shell-编程" class="headerlink" title="Shell 编程"></a>Shell 编程</h2><blockquote>
<p>由于 bash 是 Linux 标准默认的 shell，可以说  bash 是 shell 编程的基础。</p>
<p>所以，下面将全部基于 bash 来讲解 shell 编程。</p>
<p>此外，本篇章主要介绍的是 shell 编程的语法，对于 linux 指令不做任何介绍。</p>
</blockquote>
<h3 id="解释器"><a href="#解释器" class="headerlink" title="解释器"></a>解释器</h3><p>前面虽然两次提到了<code>#!</code> ，但是本着重要的事情说三遍的精神，这里再强调一遍：</p>
<p>在 shell 脚本，<code>#!</code> 告诉系统其后路径所指定的程序即是解释此脚本文件的 Shell 解释器。<code>#!</code> 被称作<a href="https://zh.wikipedia.org/wiki/Shebang" target="_blank" rel="noopener">shebang（也称为 Hashbang ）</a>。</p>
<p><code>#!</code> 决定了脚本可以像一个独立的可执行文件一样执行，而不用在终端之前输入<code>sh</code>, <code>bash</code>, <code>python</code>, <code>php</code>等。</p>
<p><strong>示例：</strong></p>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 以下两种方式都可以指定 shell 解释器为 bash，第二种方式更好</span></span><br><span class="line"><span class="meta">#!/bin/bash</span></span><br><span class="line"><span class="meta">#!/usr/bin/env bash</span></span><br></pre></td></tr></table></figure>
<h3 id="注释"><a href="#注释" class="headerlink" title="注释"></a>注释</h3><p>shell 语法支持注释。注释是特殊的语句，会被 shell 解释器忽略。它们以 <code>#</code> 开头，到行尾结束。</p>
<p><strong>示例：</strong></p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#!/bin/bash</span></span><br><span class="line"><span class="comment">### This script will print your username.</span></span><br><span class="line">whoami</span><br></pre></td></tr></table></figure>
<blockquote>
<p><strong>Tip</strong>: 用注释来说明你的脚本是干什么的，以及为什么这样写。</p>
</blockquote>
<h3 id="变量"><a href="#变量" class="headerlink" title="变量"></a>变量</h3><p>跟许多程序设计语言一样，你可以在 bash 中创建变量。</p>
<p>Bash 中没有数据类型，bash 中的变量可以保存一个数字、一个字符、一个字符串等等。同时无需提前声明变量，给变量赋值会直接创建变量。</p>
<p>你可以创建三种变量：<strong>局部变量</strong>，<strong>环境变量</strong>以及作为<strong>位置参数</strong>的变量。</p>
<h4 id="局部变量"><a href="#局部变量" class="headerlink" title="局部变量"></a>局部变量</h4><blockquote>
<p><strong>局部变量</strong>是仅在某个脚本内部有效的变量。它们不能被其他的程序和脚本访问。</p>
<p>局部变量可以<strong>用 <code>=</code> 声明</strong>（作为一种约定，变量名、<code>=</code>、变量的值之间<strong>不应该</strong>有空格），其值可以<strong>用<code>$</code> 访问</strong>到。</p>
</blockquote>
<p><strong>示例：</strong></p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">username=<span class="string">"zhangpeng"</span>  <span class="comment">### 声明变量</span></span><br><span class="line"><span class="built_in">echo</span> <span class="variable">$username</span>          <span class="comment">### 输出变量的值</span></span><br><span class="line"><span class="built_in">unset</span> username          <span class="comment">### 删除变量</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>可以<strong>用 <code>local</code> 关键字声明属于某个函数的局部变量</strong>。这样声明的变量会在函数结束时消失。</p>
</blockquote>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">local</span> local_var=<span class="string">"I'm a local value"</span></span><br></pre></td></tr></table></figure>
<h4 id="环境变量"><a href="#环境变量" class="headerlink" title="环境变量"></a>环境变量</h4><blockquote>
<p><strong>环境变量</strong>是对当前 shell 会话内所有的程序或脚本都可见的变量。</p>
<p>创建它们跟创建局部变量类似，但使用的是 <code>export</code> 关键字。</p>
</blockquote>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">export</span> global_var=<span class="string">"I'm a global value"</span></span><br></pre></td></tr></table></figure>
<p>常见的环境变量：</p>
<table>
<thead>
<tr>
<th>变量</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>$HOME</code></td>
<td>当前用户的用户目录</td>
</tr>
<tr>
<td><code>$PATH</code></td>
<td>用分号分隔的目录列表，shell会到这些目录中查找命令</td>
</tr>
<tr>
<td><code>$PWD</code></td>
<td>当前工作目录</td>
</tr>
<tr>
<td><code>$RANDOM</code></td>
<td>0到32767之间的整数</td>
</tr>
<tr>
<td><code>$UID</code></td>
<td>数值类型，当前用户的用户ID</td>
</tr>
<tr>
<td><code>$PS1</code></td>
<td>主要系统输入提示符</td>
</tr>
<tr>
<td><code>$PS2</code></td>
<td>次要系统输入提示符</td>
</tr>
</tbody>
</table>
<p><a href="http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_03_02.html###sect_03_02_04" target="_blank" rel="noopener">这里</a> 有一张更全面的 Bash 环境变量列表。</p>
<h4 id="位置参数"><a href="#位置参数" class="headerlink" title="位置参数"></a>位置参数</h4><blockquote>
<p><strong>位置参数</strong>是在调用一个函数并传给它参数时创建的变量。</p>
</blockquote>
<p>位置参数变量表：</p>
<table>
<thead>
<tr>
<th>变量</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>$0</code></td>
<td>脚本名称</td>
</tr>
<tr>
<td><code>$1 … $9</code></td>
<td>第1个到第9个参数列表</td>
</tr>
<tr>
<td><code>${10} … ${N}</code></td>
<td>第10个到N个参数列表</td>
</tr>
<tr>
<td><code>$*</code> or <code>$@</code></td>
<td>除了<code>$0</code>外的所有位置参数</td>
</tr>
<tr>
<td><code>$#</code></td>
<td>不包括<code>$0</code>在内的位置参数的个数</td>
</tr>
<tr>
<td><code>$FUNCNAME</code></td>
<td>函数名称（仅在函数内部有值）</td>
</tr>
</tbody>
</table>
<p><strong>示例：</strong></p>
<p>在下面的例子中，位置参数为：<code>$0=&#39;./script.sh&#39;</code>，<code>$1=&#39;foo&#39;</code>，<code>$2=&#39;bar&#39;</code>：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ ./script.sh foo bar</span><br></pre></td></tr></table></figure>
<p>变量可以有<strong>默认值</strong>。我们可以用如下语法来指定默认值：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">### 如果变量为空，赋给他们默认值</span></span><br><span class="line">: <span class="variable">$&#123;VAR:='default'&#125;</span></span><br><span class="line">: <span class="variable">$&#123;1:='first'&#125;</span></span><br><span class="line"><span class="built_in">echo</span> <span class="string">"\$1 : "</span> <span class="variable">$1</span></span><br><span class="line">: <span class="variable">$&#123;2:='second'&#125;</span></span><br><span class="line"><span class="built_in">echo</span> <span class="string">"\$2 : "</span> <span class="variable">$2</span></span><br><span class="line"></span><br><span class="line"><span class="comment">### 或者</span></span><br><span class="line">FOO=<span class="variable">$&#123;FOO:-'default'&#125;</span></span><br></pre></td></tr></table></figure>
<h3 id="Shell扩展"><a href="#Shell扩展" class="headerlink" title="Shell扩展"></a>Shell扩展</h3><p><em>扩展</em> 发生在一行命令被分成一个个的 <em>记号（tokens）</em> 之后。换言之，扩展是一种执行数学运算的机制，还可以用来保存命令的执行结果，等等。</p>
<p>感兴趣的话可以阅读<a href="https://www.gnu.org/software/bash/manual/bash.html###Shell-Expansions" target="_blank" rel="noopener">关于shell扩展的更多细节</a>。</p>
<h4 id="大括号扩展"><a href="#大括号扩展" class="headerlink" title="大括号扩展"></a>大括号扩展</h4><p>大括号扩展让生成任意的字符串成为可能。它跟 <em>文件名扩展</em> 很类似，举个例子：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">echo</span> beg&#123;i,a,u&#125;n <span class="comment">### begin began begun</span></span><br></pre></td></tr></table></figure>
<p>大括号扩展还可以用来创建一个可被循环迭代的区间。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">echo</span> &#123;0..5&#125; <span class="comment">### 0 1 2 3 4 5</span></span><br><span class="line"><span class="built_in">echo</span> &#123;00..8..2&#125; <span class="comment">### 00 02 04 06 08</span></span><br></pre></td></tr></table></figure>
<h4 id="命令置换"><a href="#命令置换" class="headerlink" title="命令置换"></a>命令置换</h4><p>命令置换允许我们对一个命令求值，并将其值置换到另一个命令或者变量赋值表达式中。当一个命令被<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">```bash</span><br><span class="line">now=`date +%T`</span><br><span class="line">### or</span><br><span class="line">now=$(date +%T)</span><br><span class="line"></span><br><span class="line">echo $now ### 19:08:26</span><br></pre></td></tr></table></figure></p>
<h4 id="算数扩展"><a href="#算数扩展" class="headerlink" title="算数扩展"></a>算数扩展</h4><p>在bash中，执行算数运算是非常方便的。算数表达式必须包在<code>$(( ))</code>中。算数扩展的格式为：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">result=$(( ((10 + 5*3) - 7) / 2 ))</span><br><span class="line"><span class="built_in">echo</span> <span class="variable">$result</span> <span class="comment">### 9</span></span><br></pre></td></tr></table></figure>
<p>在算数表达式中，使用变量无需带上<code>$</code>前缀：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">x=4</span><br><span class="line">y=7</span><br><span class="line"><span class="built_in">echo</span> $(( x + y ))     <span class="comment">### 11</span></span><br><span class="line"><span class="built_in">echo</span> $(( ++x + y++ )) <span class="comment">### 12</span></span><br><span class="line"><span class="built_in">echo</span> $(( x + y ))     <span class="comment">### 13</span></span><br></pre></td></tr></table></figure>
<h4 id="单引号和双引号"><a href="#单引号和双引号" class="headerlink" title="单引号和双引号"></a>单引号和双引号</h4><p>单引号和双引号之间有很重要的区别。在双引号中，变量引用或者命令置换是会被展开的。在单引号中是不会的。举个例子：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">echo</span> <span class="string">"Your home: <span class="variable">$HOME</span>"</span> <span class="comment">### Your home: /Users/&lt;username&gt;</span></span><br><span class="line"><span class="built_in">echo</span> <span class="string">'Your home: $HOME'</span> <span class="comment">### Your home: $HOME</span></span><br></pre></td></tr></table></figure>
<p>当局部变量和环境变量包含空格时，它们在引号中的扩展要格外注意。随便举个例子，假如我们用<code>echo</code>来输出用户的输入：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">INPUT=<span class="string">"A string  with   strange    whitespace."</span></span><br><span class="line"><span class="built_in">echo</span> <span class="variable">$INPUT</span>   <span class="comment">### A string with strange whitespace.</span></span><br><span class="line"><span class="built_in">echo</span> <span class="string">"<span class="variable">$INPUT</span>"</span> <span class="comment">### A string  with   strange    whitespace.</span></span><br></pre></td></tr></table></figure>
<p>调用第一个<code>echo</code>时给了它5个单独的参数 —— <code>$INPUT</code> 被分成了单独的词，<code>echo</code>在每个词之间打印了一个空格。第二种情况，调用<code>echo</code>时只给了它一个参数（整个$INPUT的值，包括其中的空格）。</p>
<p>来看一个更严肃的例子：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">FILE=<span class="string">"Favorite Things.txt"</span></span><br><span class="line">cat <span class="variable">$FILE</span>   <span class="comment">### 尝试输出两个文件: `Favorite` 和 `Things.txt`</span></span><br><span class="line">cat <span class="string">"<span class="variable">$FILE</span>"</span> <span class="comment">### 输出一个文件: `Favorite Things.txt`</span></span><br></pre></td></tr></table></figure>
<p>尽管这个问题可以通过把FILE重命名成<code>Favorite-Things.txt</code>来解决，但是，假如这个值来自某个环境变量，来自一个位置参数，或者来自其它命令（<code>find</code>, <code>cat</code>, 等等）呢。因此，如果输入 <em>可能</em> 包含空格，务必要用引号把表达式包起来。</p>
<h3 id="数组"><a href="#数组" class="headerlink" title="数组"></a>数组</h3><p>跟其它程序设计语言一样，bash中的数组变量给了你引用多个值的能力。在bash中，数组下标也是从0开始，也就是说，第一个元素的下标是0。</p>
<p>跟数组打交道时，要注意一个特殊的环境变量<code>IFS</code>。<strong>IFS</strong>，全称 <strong>Input Field Separator</strong>，保存了数组中元素的分隔符。它的默认值是一个空格<code>IFS=&#39; &#39;</code>。</p>
<h4 id="创建数组"><a href="#创建数组" class="headerlink" title="创建数组"></a>创建数组</h4><p>在 bash 中有好几种方法创建一个数组</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">array[0] = val</span><br><span class="line">array[1] = val</span><br><span class="line">array[2] = val</span><br><span class="line">array=([2]=val [0]=val [1]=val)</span><br><span class="line">array=(val val val)</span><br></pre></td></tr></table></figure>
<h4 id="获取数组元素"><a href="#获取数组元素" class="headerlink" title="获取数组元素"></a>获取数组元素</h4><ul>
<li><strong>获取数组的单个元素：</strong></li>
</ul>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">echo</span> <span class="variable">$&#123;array[1]&#125;</span></span><br></pre></td></tr></table></figure>
<ul>
<li><strong>获取数组的所有元素：</strong></li>
</ul>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">echo</span> <span class="variable">$&#123;array[*]&#125;</span></span><br><span class="line"><span class="built_in">echo</span> <span class="variable">$&#123;array[@]&#125;</span></span><br></pre></td></tr></table></figure>
<p>上面两行有很重要（也很微妙）的区别，假设某数组元素中包含空格：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">colors[0]=Red</span><br><span class="line">colors[1]=<span class="string">"Dark Green"</span></span><br><span class="line">colors[2]=Blue</span><br></pre></td></tr></table></figure>
<p>为了将数组中每个元素单独一行输出，我们用内建的<code>printf</code>命令：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">printf</span> <span class="string">"+ %s\n"</span> <span class="variable">$&#123;colors[*]&#125;</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 输出：</span></span><br><span class="line"><span class="comment"># + Red</span></span><br><span class="line"><span class="comment"># + Dark</span></span><br><span class="line"><span class="comment"># + Green</span></span><br><span class="line"><span class="comment"># + Blue</span></span><br></pre></td></tr></table></figure>
<p>为什么<code>Desert</code>和<code>fig</code>各占了一行？尝试用引号包起来：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">printf</span> <span class="string">"+ %s\n"</span> <span class="string">"<span class="variable">$&#123;colors[*]&#125;</span>"</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 输出：</span></span><br><span class="line"><span class="comment"># + Red Dark Green Blue</span></span><br></pre></td></tr></table></figure>
<p>现在所有的元素都跑去了一行 —— 这不是我们想要的！为了解决这个痛点，<code>${colors[@]}</code>闪亮登场：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">printf</span> <span class="string">"+ %s\n"</span> <span class="string">"<span class="variable">$&#123;colors[@]&#125;</span>"</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 输出：</span></span><br><span class="line">+ Red</span><br><span class="line">+ Dark Green</span><br><span class="line">+ Blue</span><br></pre></td></tr></table></figure>
<p>在引号内，<code>${colors[@]}</code>将数组中的每个元素扩展为一个单独的参数；数组元素中的空格得以保留。</p>
<ul>
<li><strong>访问数组的部分元素：</strong></li>
</ul>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">echo</span> <span class="variable">$&#123;array[@]:0:2&#125;</span></span><br></pre></td></tr></table></figure>
<p>在上面的例子中，<code>${array[@]}</code> 扩展为整个数组，<code>:0:2</code>取出了数组中从0开始，长度为2的元素。</p>
<h4 id="获取数组长度"><a href="#获取数组长度" class="headerlink" title="获取数组长度"></a>获取数组长度</h4><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">echo</span> <span class="variable">$&#123;#array[*]&#125;</span></span><br></pre></td></tr></table></figure>
<h4 id="向数组中添加元素"><a href="#向数组中添加元素" class="headerlink" title="向数组中添加元素"></a>向数组中添加元素</h4><p>向数组中添加元素也非常简单：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">colors=(Yellow <span class="string">"<span class="variable">$&#123;colors[@]&#125;</span>"</span> Pink Black)</span><br><span class="line"><span class="built_in">echo</span> <span class="variable">$&#123;colors[@]&#125;</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 输出：</span></span><br><span class="line"><span class="comment"># Yellow Red Dark Green Blue Pink Black</span></span><br></pre></td></tr></table></figure>
<p>上面的例子中，<code>${colors[@]}</code> 扩展为整个数组，并被置换到复合赋值语句中，接着，对数组<code>colors</code>的赋值覆盖了它原来的值。</p>
<h4 id="从数组中删除元素"><a href="#从数组中删除元素" class="headerlink" title="从数组中删除元素"></a>从数组中删除元素</h4><p>用<code>unset</code>命令来从数组中删除一个元素：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">unset</span> colors[0]</span><br><span class="line"><span class="built_in">echo</span> <span class="variable">$&#123;colors[@]&#125;</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 输出：</span></span><br><span class="line"><span class="comment"># Red Dark Green Blue Pink Black</span></span><br></pre></td></tr></table></figure>
<h3 id="运算符"><a href="#运算符" class="headerlink" title="运算符"></a>运算符</h3><h4 id="算术运算符"><a href="#算术运算符" class="headerlink" title="算术运算符"></a>算术运算符</h4><p>下表列出了常用的算术运算符，假定变量 a 为 10，变量 b 为 20：</p>
<table>
<thead>
<tr>
<th>运算符</th>
<th>说明</th>
<th>举例</th>
</tr>
</thead>
<tbody>
<tr>
<td>+</td>
<td>加法</td>
<td><code>expr $a + $b</code> 结果为 30。</td>
</tr>
<tr>
<td>-</td>
<td>减法</td>
<td><code>expr $a - $b</code> 结果为 -10。</td>
</tr>
<tr>
<td>*</td>
<td>乘法</td>
<td><code>expr $a \* $b</code> 结果为  200。</td>
</tr>
<tr>
<td>/</td>
<td>除法</td>
<td><code>expr $b / $a</code> 结果为 2。</td>
</tr>
<tr>
<td>%</td>
<td>取余</td>
<td><code>expr $b % $a</code> 结果为 0。</td>
</tr>
<tr>
<td>=</td>
<td>赋值</td>
<td><code>a=$b</code> 将把变量 b 的值赋给 a。</td>
</tr>
<tr>
<td>==</td>
<td>相等。用于比较两个数字，相同则返回 true。</td>
<td><code>[ $a == $b ]</code> 返回 false。</td>
</tr>
<tr>
<td>!=</td>
<td>不相等。用于比较两个数字，不相同则返回 true。</td>
<td><code>[ $a != $b ]</code> 返回 true。</td>
</tr>
</tbody>
</table>
<p><strong>注意：</strong>条件表达式要放在方括号之间，并且要有空格，例如: <strong>[$a==$b]</strong> 是错误的，必须写成 <strong>[ $a == $b ]</strong>。</p>
<p><strong>示例：</strong></p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line">a=10</span><br><span class="line">b=20</span><br><span class="line"></span><br><span class="line"><span class="built_in">echo</span> <span class="string">"a=<span class="variable">$a</span>, b=<span class="variable">$b</span>"</span></span><br><span class="line"></span><br><span class="line">val=`expr <span class="variable">$a</span> + <span class="variable">$b</span>`</span><br><span class="line"><span class="built_in">echo</span> <span class="string">"a + b : <span class="variable">$val</span>"</span></span><br><span class="line"></span><br><span class="line">val=`expr <span class="variable">$a</span> - <span class="variable">$b</span>`</span><br><span class="line"><span class="built_in">echo</span> <span class="string">"a - b : <span class="variable">$val</span>"</span></span><br><span class="line"></span><br><span class="line">val=`expr <span class="variable">$a</span> \* <span class="variable">$b</span>`</span><br><span class="line"><span class="built_in">echo</span> <span class="string">"a * b : <span class="variable">$val</span>"</span></span><br><span class="line"></span><br><span class="line">val=`expr <span class="variable">$b</span> / <span class="variable">$a</span>`</span><br><span class="line"><span class="built_in">echo</span> <span class="string">"b / a : <span class="variable">$val</span>"</span></span><br><span class="line"></span><br><span class="line">val=`expr <span class="variable">$b</span> % <span class="variable">$a</span>`</span><br><span class="line"><span class="built_in">echo</span> <span class="string">"b % a : <span class="variable">$val</span>"</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> [ <span class="variable">$a</span> == <span class="variable">$b</span> ]</span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">  <span class="built_in">echo</span> <span class="string">"a 等于 b"</span></span><br><span class="line"><span class="keyword">fi</span></span><br><span class="line"><span class="keyword">if</span> [ <span class="variable">$a</span> != <span class="variable">$b</span> ]</span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">  <span class="built_in">echo</span> <span class="string">"a 不等于 b"</span></span><br><span class="line"><span class="keyword">fi</span></span><br></pre></td></tr></table></figure>
<h4 id="关系运算符"><a href="#关系运算符" class="headerlink" title="关系运算符"></a>关系运算符</h4><p>关系运算符只支持数字，不支持字符串，除非字符串的值是数字。</p>
<p>下表列出了常用的关系运算符，假定变量 a 为 10，变量 b 为 20：</p>
<table>
<thead>
<tr>
<th>运算符</th>
<th>说明</th>
<th>举例</th>
</tr>
</thead>
<tbody>
<tr>
<td>-eq</td>
<td>检测两个数是否相等，相等返回 true。</td>
<td><code>[ $a -eq $b ]</code>返回 false。</td>
</tr>
<tr>
<td>-ne</td>
<td>检测两个数是否相等，不相等返回 true。</td>
<td><code>[ $a -ne $b ]</code> 返回 true。</td>
</tr>
<tr>
<td>-gt</td>
<td>检测左边的数是否大于右边的，如果是，则返回 true。</td>
<td><code>[ $a -gt $b ]</code> 返回 false。</td>
</tr>
<tr>
<td>-lt</td>
<td>检测左边的数是否小于右边的，如果是，则返回 true。</td>
<td><code>[ $a -lt $b ]</code> 返回 true。</td>
</tr>
<tr>
<td>-ge</td>
<td>检测左边的数是否大于等于右边的，如果是，则返回 true。</td>
<td><code>[ $a -ge $b ]</code> 返回 false。</td>
</tr>
<tr>
<td>-le</td>
<td>检测左边的数是否小于等于右边的，如果是，则返回 true。</td>
<td><code>[ $a -le $b ]</code>返回 true。</td>
</tr>
</tbody>
</table>
<p><strong>示例：</strong></p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line">a=10</span><br><span class="line">b=20</span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> [ <span class="variable">$a</span> -eq <span class="variable">$b</span> ]</span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"<span class="variable">$a</span> -eq <span class="variable">$b</span> : a 等于 b"</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"<span class="variable">$a</span> -eq <span class="variable">$b</span>: a 不等于 b"</span></span><br><span class="line"><span class="keyword">fi</span></span><br><span class="line"><span class="keyword">if</span> [ <span class="variable">$a</span> -ne <span class="variable">$b</span> ]</span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"<span class="variable">$a</span> -ne <span class="variable">$b</span>: a 不等于 b"</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"<span class="variable">$a</span> -ne <span class="variable">$b</span> : a 等于 b"</span></span><br><span class="line"><span class="keyword">fi</span></span><br><span class="line"><span class="keyword">if</span> [ <span class="variable">$a</span> -gt <span class="variable">$b</span> ]</span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"<span class="variable">$a</span> -gt <span class="variable">$b</span>: a 大于 b"</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"<span class="variable">$a</span> -gt <span class="variable">$b</span>: a 不大于 b"</span></span><br><span class="line"><span class="keyword">fi</span></span><br><span class="line"><span class="keyword">if</span> [ <span class="variable">$a</span> -lt <span class="variable">$b</span> ]</span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"<span class="variable">$a</span> -lt <span class="variable">$b</span>: a 小于 b"</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"<span class="variable">$a</span> -lt <span class="variable">$b</span>: a 不小于 b"</span></span><br><span class="line"><span class="keyword">fi</span></span><br><span class="line"><span class="keyword">if</span> [ <span class="variable">$a</span> -ge <span class="variable">$b</span> ]</span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"<span class="variable">$a</span> -ge <span class="variable">$b</span>: a 大于或等于 b"</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"<span class="variable">$a</span> -ge <span class="variable">$b</span>: a 小于 b"</span></span><br><span class="line"><span class="keyword">fi</span></span><br><span class="line"><span class="keyword">if</span> [ <span class="variable">$a</span> -le <span class="variable">$b</span> ]</span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"<span class="variable">$a</span> -le <span class="variable">$b</span>: a 小于或等于 b"</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"<span class="variable">$a</span> -le <span class="variable">$b</span>: a 大于 b"</span></span><br><span class="line"><span class="keyword">fi</span></span><br></pre></td></tr></table></figure>
<h4 id="布尔运算符"><a href="#布尔运算符" class="headerlink" title="布尔运算符"></a>布尔运算符</h4><p>下表列出了常用的布尔运算符，假定变量 a 为 10，变量 b 为 20：</p>
<table>
<thead>
<tr>
<th>运算符</th>
<th>说明</th>
<th>举例</th>
</tr>
</thead>
<tbody>
<tr>
<td>!</td>
<td>非运算，表达式为 true 则返回 false，否则返回 true。</td>
<td><code>[ ! false ]</code> 返回 true。</td>
</tr>
<tr>
<td>-o</td>
<td>或运算，有一个表达式为 true 则返回 true。</td>
<td><code>[ $a -lt 20 -o $b -gt 100 ]</code> 返回 true。</td>
</tr>
<tr>
<td>-a</td>
<td>与运算，两个表达式都为 true 才返回 true。</td>
<td><code>[ $a -lt 20 -a $b -gt 100 ]</code> 返回 false。</td>
</tr>
</tbody>
</table>
<p><strong>示例：</strong></p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line">a=10</span><br><span class="line">b=20</span><br><span class="line"></span><br><span class="line"><span class="built_in">echo</span> <span class="string">"a=<span class="variable">$a</span>, b=<span class="variable">$b</span>"</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> [ <span class="variable">$a</span> != <span class="variable">$b</span> ]</span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"<span class="variable">$a</span> != <span class="variable">$b</span> : a 不等于 b"</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"<span class="variable">$a</span> != <span class="variable">$b</span>: a 等于 b"</span></span><br><span class="line"><span class="keyword">fi</span></span><br><span class="line"><span class="keyword">if</span> [ <span class="variable">$a</span> -lt 100 -a <span class="variable">$b</span> -gt 15 ]</span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"<span class="variable">$a</span> 小于 100 且 <span class="variable">$b</span> 大于 15 : 返回 true"</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"<span class="variable">$a</span> 小于 100 且 <span class="variable">$b</span> 大于 15 : 返回 false"</span></span><br><span class="line"><span class="keyword">fi</span></span><br><span class="line"><span class="keyword">if</span> [ <span class="variable">$a</span> -lt 100 -o <span class="variable">$b</span> -gt 100 ]</span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"<span class="variable">$a</span> 小于 100 或 <span class="variable">$b</span> 大于 100 : 返回 true"</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"<span class="variable">$a</span> 小于 100 或 <span class="variable">$b</span> 大于 100 : 返回 false"</span></span><br><span class="line"><span class="keyword">fi</span></span><br><span class="line"><span class="keyword">if</span> [ <span class="variable">$a</span> -lt 5 -o <span class="variable">$b</span> -gt 100 ]</span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"<span class="variable">$a</span> 小于 5 或 <span class="variable">$b</span> 大于 100 : 返回 true"</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"<span class="variable">$a</span> 小于 5 或 <span class="variable">$b</span> 大于 100 : 返回 false"</span></span><br><span class="line"><span class="keyword">fi</span></span><br></pre></td></tr></table></figure>
<h4 id="逻辑运算符"><a href="#逻辑运算符" class="headerlink" title="逻辑运算符"></a>逻辑运算符</h4><p>以下介绍 Shell 的逻辑运算符，假定变量 a 为 10，变量 b 为 20:</p>
<table>
<thead>
<tr>
<th>运算符</th>
<th>说明</th>
<th>举例</th>
</tr>
</thead>
<tbody>
<tr>
<td>&amp;&amp;</td>
<td>逻辑的 AND</td>
<td><code>[[ $a -lt 100 &amp;&amp; $b -gt 100 ]]</code> 返回 false</td>
</tr>
<tr>
<td>\</td>
<td>\</td>
<td></td>
<td>逻辑的 OR</td>
<td>`[[ $a -lt 100</td>
<td></td>
<td>$b -gt 100 ]]` 返回 true</td>
</tr>
</tbody>
</table>
<p><strong>示例：</strong></p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">a=10</span><br><span class="line">b=20</span><br><span class="line"></span><br><span class="line"><span class="built_in">echo</span> <span class="string">"a=<span class="variable">$a</span>, b=<span class="variable">$b</span>"</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> [[ <span class="variable">$a</span> -lt 100 &amp;&amp; <span class="variable">$b</span> -gt 100 ]]</span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"返回 true"</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"返回 false"</span></span><br><span class="line"><span class="keyword">fi</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> [[ <span class="variable">$a</span> -lt 100 || <span class="variable">$b</span> -gt 100 ]]</span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"返回 true"</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"返回 false"</span></span><br><span class="line"><span class="keyword">fi</span></span><br></pre></td></tr></table></figure>
<h4 id="字符串运算符"><a href="#字符串运算符" class="headerlink" title="字符串运算符"></a>字符串运算符</h4><p>下表列出了常用的字符串运算符，假定变量 a 为 “abc”，变量 b 为 “efg”：</p>
<table>
<thead>
<tr>
<th>运算符</th>
<th>说明</th>
<th>举例</th>
</tr>
</thead>
<tbody>
<tr>
<td>=</td>
<td>检测两个字符串是否相等，相等返回 true。</td>
<td><code>[ $a = $b ]</code> 返回 false。</td>
</tr>
<tr>
<td>!=</td>
<td>检测两个字符串是否相等，不相等返回 true。</td>
<td><code>[ $a != $b ]</code> 返回 true。</td>
</tr>
<tr>
<td>-z</td>
<td>检测字符串长度是否为0，为0返回 true。</td>
<td><code>[ -z $a ]</code> 返回 false。</td>
</tr>
<tr>
<td>-n</td>
<td>检测字符串长度是否为0，不为0返回 true。</td>
<td><code>[ -n $a ]</code> 返回 true。</td>
</tr>
<tr>
<td>str</td>
<td>检测字符串是否为空，不为空返回 true。</td>
<td><code>[ $a ]</code> 返回 true。</td>
</tr>
</tbody>
</table>
<p><strong>示例：</strong></p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line">a=<span class="string">"abc"</span></span><br><span class="line">b=<span class="string">"efg"</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">echo</span> <span class="string">"a=<span class="variable">$a</span>, b=<span class="variable">$b</span>"</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> [ <span class="variable">$a</span> = <span class="variable">$b</span> ]</span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"<span class="variable">$a</span> = <span class="variable">$b</span> : a 等于 b"</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"<span class="variable">$a</span> = <span class="variable">$b</span>: a 不等于 b"</span></span><br><span class="line"><span class="keyword">fi</span></span><br><span class="line"><span class="keyword">if</span> [ <span class="variable">$a</span> != <span class="variable">$b</span> ]</span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"<span class="variable">$a</span> != <span class="variable">$b</span> : a 不等于 b"</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"<span class="variable">$a</span> != <span class="variable">$b</span>: a 等于 b"</span></span><br><span class="line"><span class="keyword">fi</span></span><br><span class="line"><span class="keyword">if</span> [ -z <span class="variable">$a</span> ]</span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"-z <span class="variable">$a</span> : 字符串长度为 0"</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"-z <span class="variable">$a</span> : 字符串长度不为 0"</span></span><br><span class="line"><span class="keyword">fi</span></span><br><span class="line"><span class="keyword">if</span> [ -n <span class="variable">$a</span> ]</span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"-n <span class="variable">$a</span> : 字符串长度不为 0"</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"-n <span class="variable">$a</span> : 字符串长度为 0"</span></span><br><span class="line"><span class="keyword">fi</span></span><br><span class="line"><span class="keyword">if</span> [ <span class="variable">$a</span> ]</span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"<span class="variable">$a</span> : 字符串不为空"</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"<span class="variable">$a</span> : 字符串为空"</span></span><br><span class="line"><span class="keyword">fi</span></span><br></pre></td></tr></table></figure>
<h4 id="文件测试运算符"><a href="#文件测试运算符" class="headerlink" title="文件测试运算符"></a>文件测试运算符</h4><p>文件测试运算符用于检测 Unix 文件的各种属性。</p>
<p>属性检测描述如下：</p>
<table>
<thead>
<tr>
<th>操作符</th>
<th>说明</th>
<th>举例</th>
</tr>
</thead>
<tbody>
<tr>
<td>-b file</td>
<td>检测文件是否是块设备文件，如果是，则返回 true。</td>
<td><code>[ -b $file ]</code> 返回 false。</td>
</tr>
<tr>
<td>-c file</td>
<td>检测文件是否是字符设备文件，如果是，则返回 true。</td>
<td><code>[ -c $file ]</code> 返回 false。</td>
</tr>
<tr>
<td>-d file</td>
<td>检测文件是否是目录，如果是，则返回 true。</td>
<td><code>[ -d $file ]</code> 返回 false。</td>
</tr>
<tr>
<td>-f file</td>
<td>检测文件是否是普通文件（既不是目录，也不是设备文件），如果是，则返回 true。</td>
<td><code>[ -f $file ]</code> 返回 true。</td>
</tr>
<tr>
<td>-g file</td>
<td>检测文件是否设置了 SGID 位，如果是，则返回 true。</td>
<td><code>[ -g $file ]</code> 返回 false。</td>
</tr>
<tr>
<td>-k file</td>
<td>检测文件是否设置了粘着位(Sticky Bit)，如果是，则返回 true。</td>
<td><code>[ -k $file ]</code>返回 false。</td>
</tr>
<tr>
<td>-p file</td>
<td>检测文件是否是有名管道，如果是，则返回 true。</td>
<td><code>[ -p $file ]</code> 返回 false。</td>
</tr>
<tr>
<td>-u file</td>
<td>检测文件是否设置了 SUID 位，如果是，则返回 true。</td>
<td><code>[ -u $file ]</code> 返回 false。</td>
</tr>
<tr>
<td>-r file</td>
<td>检测文件是否可读，如果是，则返回 true。</td>
<td><code>[ -r $file ]</code> 返回 true。</td>
</tr>
<tr>
<td>-w file</td>
<td>检测文件是否可写，如果是，则返回 true。</td>
<td><code>[ -w $file ]</code> 返回 true。</td>
</tr>
<tr>
<td>-x file</td>
<td>检测文件是否可执行，如果是，则返回 true。</td>
<td><code>[ -x $file ]</code> 返回 true。</td>
</tr>
<tr>
<td>-s file</td>
<td>检测文件是否为空（文件大小是否大于0），不为空返回 true。</td>
<td><code>[ -s $file ]</code> 返回 true。</td>
</tr>
<tr>
<td>-e file</td>
<td>检测文件（包括目录）是否存在，如果是，则返回 true。</td>
<td><code>[ -e $file ]</code> 返回 true。</td>
</tr>
</tbody>
</table>
<p><strong>示例：</strong></p>
<p>变量 file 表示文件”/var/www/runoob/test.sh”，它的大小为100字节，具有 rwx 权限。下面的代码，将检测该文件的各种属性：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line">file=<span class="string">"./operatorDemo.sh"</span></span><br><span class="line"><span class="keyword">if</span> [ -r <span class="variable">$file</span> ]</span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"文件可读"</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"文件不可读"</span></span><br><span class="line"><span class="keyword">fi</span></span><br><span class="line"><span class="keyword">if</span> [ -w <span class="variable">$file</span> ]</span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"文件可写"</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"文件不可写"</span></span><br><span class="line"><span class="keyword">fi</span></span><br><span class="line"><span class="keyword">if</span> [ -x <span class="variable">$file</span> ]</span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"文件可执行"</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"文件不可执行"</span></span><br><span class="line"><span class="keyword">fi</span></span><br><span class="line"><span class="keyword">if</span> [ -f <span class="variable">$file</span> ]</span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"文件为普通文件"</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"文件为特殊文件"</span></span><br><span class="line"><span class="keyword">fi</span></span><br><span class="line"><span class="keyword">if</span> [ -d <span class="variable">$file</span> ]</span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"文件是个目录"</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"文件不是个目录"</span></span><br><span class="line"><span class="keyword">fi</span></span><br><span class="line"><span class="keyword">if</span> [ -s <span class="variable">$file</span> ]</span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"文件不为空"</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"文件为空"</span></span><br><span class="line"><span class="keyword">fi</span></span><br><span class="line"><span class="keyword">if</span> [ -e <span class="variable">$file</span> ]</span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"文件存在"</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"文件不存在"</span></span><br><span class="line"><span class="keyword">fi</span></span><br></pre></td></tr></table></figure>
<h3 id="语句"><a href="#语句" class="headerlink" title="语句"></a>语句</h3><h4 id="条件语句"><a href="#条件语句" class="headerlink" title="条件语句"></a>条件语句</h4><p>跟其它程序设计语言一样，Bash中的条件语句让我们可以决定一个操作是否被执行。结果取决于一个包在<code>[[ ]]</code>里的表达式。</p>
<p>条件表达式可以包含<code>&amp;&amp;</code>和<code>||</code>运算符，分别对应 <em>与</em> 和 <em>或</em> 。除此之外还有很多有用的<a href="https://github.com/denysdovhan/bash-handbook/blob/master/translations/zh-CN/README.md#%E5%9F%BA%E5%85%83%E5%92%8C%E7%BB%84%E5%90%88%E8%A1%A8%E8%BE%BE%E5%BC%8F" target="_blank" rel="noopener">表达式</a>。</p>
<p>共有两个不同的条件表达式：<code>if</code>和<code>case</code>。</p>
<h5 id="基元和组合表达式"><a href="#基元和组合表达式" class="headerlink" title="基元和组合表达式"></a>基元和组合表达式</h5><p>由<code>[[ ]]</code>（<code>sh</code>中是<code>[ ]</code>）包起来的表达式被称作 <strong>检测命令</strong> 或 <strong>基元</strong>。这些表达式帮助我们检测一个条件的结果。在下面的表里，为了兼容<code>sh</code>，我们用的是<code>[ ]</code>。这里可以找到有关<a href="http://serverfault.com/a/52050" target="_blank" rel="noopener">bash中单双中括号区别</a>的答案。</p>
<h5 id="使用if"><a href="#使用if" class="headerlink" title="使用if"></a>使用<code>if</code></h5><p><code>if</code>在使用上跟其它语言相同。如果中括号里的表达式为真，那么<code>then</code>和<code>fi</code>之间的代码会被执行。<code>fi</code>标志着条件代码块的结束。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">### 写成一行</span></span><br><span class="line"><span class="keyword">if</span> [[ 1 -eq 1 ]]; <span class="keyword">then</span> <span class="built_in">echo</span> <span class="string">"true"</span>; <span class="keyword">fi</span></span><br><span class="line"></span><br><span class="line"><span class="comment">### 写成多行</span></span><br><span class="line"><span class="keyword">if</span> [[ 1 -eq 1 ]]; <span class="keyword">then</span></span><br><span class="line">  <span class="built_in">echo</span> <span class="string">"true"</span></span><br><span class="line"><span class="keyword">fi</span></span><br></pre></td></tr></table></figure>
<p>同样，我们可以使用<code>if..else</code>语句，例如：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">### 写成一行</span></span><br><span class="line"><span class="keyword">if</span> [[ 2 -ne 1 ]]; <span class="keyword">then</span> <span class="built_in">echo</span> <span class="string">"true"</span>; <span class="keyword">else</span> <span class="built_in">echo</span> <span class="string">"false"</span>; <span class="keyword">fi</span></span><br><span class="line"></span><br><span class="line"><span class="comment">### 写成多行</span></span><br><span class="line"><span class="keyword">if</span> [[ 2 -ne 1 ]]; <span class="keyword">then</span></span><br><span class="line">  <span class="built_in">echo</span> <span class="string">"true"</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">  <span class="built_in">echo</span> <span class="string">"false"</span></span><br><span class="line"><span class="keyword">fi</span></span><br></pre></td></tr></table></figure>
<p>有些时候，<code>if..else</code>不能满足我们的要求。别忘了<code>if..elif..else</code>，使用起来也很方便。</p>
<p><strong>示例：</strong></p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> [[ `uname` == <span class="string">"Adam"</span> ]]; <span class="keyword">then</span></span><br><span class="line">  <span class="built_in">echo</span> <span class="string">"Do not eat an apple!"</span></span><br><span class="line"><span class="keyword">elif</span> [[ `uname` == <span class="string">"Eva"</span> ]]; <span class="keyword">then</span></span><br><span class="line">  <span class="built_in">echo</span> <span class="string">"Do not take an apple!"</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">  <span class="built_in">echo</span> <span class="string">"Apples are delicious!"</span></span><br><span class="line"><span class="keyword">fi</span></span><br></pre></td></tr></table></figure>
<h5 id="使用case"><a href="#使用case" class="headerlink" title="使用case"></a>使用<code>case</code></h5><p>如果你需要面对很多情况，分别要采取不同的措施，那么使用<code>case</code>会比嵌套的<code>if</code>更有用。使用<code>case</code>来解决复杂的条件判断，看起来像下面这样：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">echo</span> <span class="string">"input param: "</span> <span class="variable">$1</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">case</span> <span class="variable">$1</span> <span class="keyword">in</span></span><br><span class="line">  <span class="string">"jpg"</span> | <span class="string">"jpeg"</span>)</span><br><span class="line">    <span class="built_in">echo</span> <span class="string">"It's image with jpeg extension."</span></span><br><span class="line">  ;;</span><br><span class="line">  <span class="string">"png"</span>)</span><br><span class="line">    <span class="built_in">echo</span> <span class="string">"It's image with png extension."</span></span><br><span class="line">  ;;</span><br><span class="line">  <span class="string">"gif"</span>)</span><br><span class="line">    <span class="built_in">echo</span> <span class="string">"Oh, it's a giphy!"</span></span><br><span class="line">  ;;</span><br><span class="line">  *)</span><br><span class="line">    <span class="built_in">echo</span> <span class="string">"Woops! It's not image!"</span></span><br><span class="line">  ;;</span><br><span class="line"><span class="keyword">esac</span></span><br></pre></td></tr></table></figure>
<p>每种情况都是匹配了某个模式的表达式。<code>|</code>用来分割多个模式，<code>)</code>用来结束一个模式序列。第一个匹配上的模式对应的命令将会被执行。<code>*</code>代表任何不匹配以上给定模式的模式。命令块儿之间要用<code>;;</code>分隔。</p>
<h4 id="循环语句"><a href="#循环语句" class="headerlink" title="循环语句"></a>循环语句</h4><p>循环其实不足为奇。跟其它程序设计语言一样，bash中的循环也是只要控制条件为真就一直迭代执行的代码块。</p>
<p>Bash中有四种循环：<code>for</code>，<code>while</code>，<code>until</code>和<code>select</code>。</p>
<h5 id="for循环"><a href="#for循环" class="headerlink" title="for循环"></a><code>for</code>循环</h5><p><code>for</code>与它在C语言中的姊妹非常像。看起来是这样：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> arg <span class="keyword">in</span> elem1 elem2 ... elemN</span><br><span class="line"><span class="keyword">do</span></span><br><span class="line">  <span class="comment">### 语句</span></span><br><span class="line"><span class="keyword">done</span></span><br></pre></td></tr></table></figure>
<p>在每次循环的过程中，<code>arg</code>依次被赋值为从<code>elem1</code>到<code>elemN</code>。这些值还可以是通配符或者<a href="https://github.com/denysdovhan/bash-handbook/blob/master/translations/zh-CN/README.md#%E5%A4%A7%E6%8B%AC%E5%8F%B7%E6%89%A9%E5%B1%95" target="_blank" rel="noopener">大括号扩展</a>。</p>
<p>当然，我们还可以把<code>for</code>循环写在一行，但这要求<code>do</code>之前要有一个分号，就像下面这样：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> &#123;1..5&#125;; <span class="keyword">do</span> <span class="built_in">echo</span> <span class="variable">$i</span>; <span class="keyword">done</span></span><br></pre></td></tr></table></figure>
<p>还有，如果你觉得<code>for..in..do</code>对你来说有点奇怪，那么你也可以像C语言那样使用<code>for</code>，比如：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> (( i = 0; i &lt; 10; i++ )); <span class="keyword">do</span></span><br><span class="line">  <span class="built_in">echo</span> <span class="variable">$i</span></span><br><span class="line"><span class="keyword">done</span></span><br></pre></td></tr></table></figure>
<p>当我们想对一个目录下的所有文件做同样的操作时，<code>for</code>就很方便了。举个例子，如果我们想把所有的<code>.bash</code>文件移动到<code>script</code>文件夹中，并给它们可执行权限，我们的脚本可以这样写：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#!/bin/bash</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> FILE <span class="keyword">in</span> <span class="variable">$HOME</span>/*.bash; <span class="keyword">do</span></span><br><span class="line">  mv <span class="string">"<span class="variable">$FILE</span>"</span> <span class="string">"<span class="variable">$&#123;HOME&#125;</span>/scripts"</span></span><br><span class="line">  chmod +x <span class="string">"<span class="variable">$&#123;HOME&#125;</span>/scripts/<span class="variable">$&#123;FILE&#125;</span>"</span></span><br><span class="line"><span class="keyword">done</span></span><br></pre></td></tr></table></figure>
<h5 id="while循环"><a href="#while循环" class="headerlink" title="while循环"></a><code>while</code>循环</h5><p><code>while</code>循环检测一个条件，只要这个条件为 <em>真</em>，就执行一段命令。被检测的条件跟<code>if..then</code>中使用的<a href="https://github.com/denysdovhan/bash-handbook/blob/master/translations/zh-CN/README.md#%E5%9F%BA%E5%85%83%E5%92%8C%E7%BB%84%E5%90%88%E8%A1%A8%E8%BE%BE%E5%BC%8F" target="_blank" rel="noopener">基元</a>并无二异。因此一个<code>while</code>循环看起来会是这样：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">while</span> [[ condition ]]</span><br><span class="line"><span class="keyword">do</span></span><br><span class="line">  <span class="comment">### 语句</span></span><br><span class="line"><span class="keyword">done</span></span><br></pre></td></tr></table></figure>
<p>跟<code>for</code>循环一样，如果我们把<code>do</code>和被检测的条件写到一行，那么必须要在<code>do</code>之前加一个分号。</p>
<p>比如下面这个例子：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#!/bin/bash</span></span><br><span class="line"></span><br><span class="line"><span class="comment">### 0到9之间每个数的平方</span></span><br><span class="line">x=0</span><br><span class="line"><span class="keyword">while</span> [[ <span class="variable">$x</span> -lt 10 ]]; <span class="keyword">do</span> <span class="comment">### x小于10</span></span><br><span class="line">  <span class="built_in">echo</span> $(( x * x ))</span><br><span class="line">  x=$(( x + 1 )) <span class="comment">### x加1</span></span><br><span class="line"><span class="keyword">done</span></span><br></pre></td></tr></table></figure>
<h5 id="until循环"><a href="#until循环" class="headerlink" title="until循环"></a><code>until</code>循环</h5><p><code>until</code>循环跟<code>while</code>循环正好相反。它跟<code>while</code>一样也需要检测一个测试条件，但不同的是，只要该条件为 <em>假</em> 就一直执行循环：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">until [[ condition ]]; <span class="keyword">do</span></span><br><span class="line">  <span class="comment">### 语句</span></span><br><span class="line"><span class="keyword">done</span></span><br></pre></td></tr></table></figure>
<h5 id="select循环"><a href="#select循环" class="headerlink" title="select循环"></a><code>select</code>循环</h5><p><code>select</code>循环帮助我们组织一个用户菜单。它的语法几乎跟<code>for</code>循环一致：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">select answer <span class="keyword">in</span> elem1 elem2 ... elemN</span><br><span class="line"><span class="keyword">do</span></span><br><span class="line">  <span class="comment">### 语句</span></span><br><span class="line"><span class="keyword">done</span></span><br></pre></td></tr></table></figure>
<p><code>select</code>会打印<code>elem1..elemN</code>以及它们的序列号到屏幕上，之后会提示用户输入。通常看到的是<code>$?</code>（<code>PS3</code>变量）。用户的选择结果会被保存到<code>answer</code>中。如果<code>answer</code>是一个在<code>1..N</code>之间的数字，那么<code>语句</code>会被执行，紧接着会进行下一次迭代 —— 如果不想这样的话我们可以使用<code>break</code>语句。</p>
<p>一个可能的实例可能会是这样：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#!/bin/bash</span></span><br><span class="line"></span><br><span class="line">PS3=<span class="string">"Choose the package manager: "</span></span><br><span class="line">select ITEM <span class="keyword">in</span> bower npm gem pip</span><br><span class="line"><span class="keyword">do</span></span><br><span class="line">  <span class="built_in">echo</span> -n <span class="string">"Enter the package name: "</span> &amp;&amp; <span class="built_in">read</span> PACKAGE</span><br><span class="line">  <span class="keyword">case</span> <span class="variable">$ITEM</span> <span class="keyword">in</span></span><br><span class="line">    bower) bower install <span class="variable">$PACKAGE</span> ;;</span><br><span class="line">    npm)   npm   install <span class="variable">$PACKAGE</span> ;;</span><br><span class="line">    gem)   gem   install <span class="variable">$PACKAGE</span> ;;</span><br><span class="line">    pip)   pip   install <span class="variable">$PACKAGE</span> ;;</span><br><span class="line">  <span class="keyword">esac</span></span><br><span class="line">  <span class="built_in">break</span> <span class="comment">### 避免无限循环</span></span><br><span class="line"><span class="keyword">done</span></span><br></pre></td></tr></table></figure>
<p>这个例子，先询问用户他想使用什么包管理器。接着，又询问了想安装什么包，最后执行安装操作。</p>
<p>运行这个脚本，会得到如下输出：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">$ ./my_script</span><br><span class="line">1) bower</span><br><span class="line">2) npm</span><br><span class="line">3) gem</span><br><span class="line">4) pip</span><br><span class="line">Choose the package manager: 2</span><br><span class="line">Enter the package name: bash-handbook</span><br><span class="line">&lt;installing bash-handbook&gt;</span><br></pre></td></tr></table></figure>
<h5 id="break-和-continue"><a href="#break-和-continue" class="headerlink" title="break 和 continue"></a>break 和 continue</h5><p>如果想提前结束一个循环或跳过某次循环执行，可以使用 shell 的<code>break</code>和<code>continue</code>语句来实现。它们可以在任何循环中使用。</p>
<blockquote>
<p><code>break</code>语句用来提前结束当前循环。</p>
<p><code>continue</code>语句用来跳过某次迭代。</p>
</blockquote>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> (( i = 0; i &lt; 10; i++ )); <span class="keyword">do</span></span><br><span class="line">  <span class="keyword">if</span> [[ $(( i % 2 )) -eq 0 ]]; <span class="keyword">then</span> <span class="built_in">continue</span>; <span class="keyword">fi</span></span><br><span class="line">  <span class="built_in">echo</span> <span class="variable">$i</span></span><br><span class="line"><span class="keyword">done</span></span><br></pre></td></tr></table></figure>
<p>运行上面的例子，会打印出所有0到9之间的奇数。</p>
<h3 id="函数"><a href="#函数" class="headerlink" title="函数"></a>函数</h3><p>在脚本中，我们可以定义并调用函数。跟其它程序设计语言类似，函数是一个代码块，但有所不同。</p>
<p>bash 中，函数是一个命令序列，这个命令序列组织在某个名字下面，即 <em>函数名</em> 。调用函数跟其它语言一样，写下函数名字，函数就会被 <em>调用</em> 。</p>
<p>我们可以这样声明函数：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="title">my_func</span></span> () &#123;</span><br><span class="line">  <span class="comment">### 语句</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">my_func <span class="comment">### 调用 my_func</span></span><br></pre></td></tr></table></figure>
<p>我们必须在调用前声明函数。</p>
<p>函数可以接收参数并返回结果 —— 返回值。参数，在函数内部，跟<a href="https://github.com/denysdovhan/bash-handbook/blob/master/translations/zh-CN/README.md#%E9%9D%9E%E4%BA%A4%E4%BA%92%E6%A8%A1%E5%BC%8F" target="_blank" rel="noopener">非交互式</a>下的脚本参数处理方式相同 —— 使用<a href="https://github.com/denysdovhan/bash-handbook/blob/master/translations/zh-CN/README.md#%E4%BD%8D%E7%BD%AE%E5%8F%82%E6%95%B0" target="_blank" rel="noopener">位置参数</a>。返回值可以使用<code>return</code>命令 <em>返回</em> 。</p>
<p>下面这个函数接收一个名字参数，返回<code>0</code>，表示成功执行。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">### 带参数的函数</span></span><br><span class="line"><span class="function"><span class="title">greeting</span></span> () &#123;</span><br><span class="line">  <span class="keyword">if</span> [[ -n <span class="variable">$1</span> ]]; <span class="keyword">then</span></span><br><span class="line">    <span class="built_in">echo</span> <span class="string">"Hello, <span class="variable">$1</span>!"</span></span><br><span class="line">  <span class="keyword">else</span></span><br><span class="line">    <span class="built_in">echo</span> <span class="string">"Hello, unknown!"</span></span><br><span class="line">  <span class="keyword">fi</span></span><br><span class="line">  <span class="built_in">return</span> 0</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">greeting Denys  <span class="comment">### Hello, Denys!</span></span><br><span class="line">greeting        <span class="comment">### Hello, stranger!</span></span><br></pre></td></tr></table></figure>
<p>我们之前已经介绍过<a href="https://github.com/denysdovhan/bash-handbook/blob/master/translations/zh-CN/README.md#%E8%BF%94%E5%9B%9E%E5%80%BC" target="_blank" rel="noopener">返回值</a>。不带任何参数的<code>return</code>会返回最后一个执行的命令的返回值。上面的例子，<code>return 0</code>会返回一个成功表示执行的值，<code>0</code>。</p>
<p>另外，还有几个特殊字符用来处理参数：</p>
<table>
<thead>
<tr>
<th>参数处理</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td>$#</td>
<td>传递到脚本的参数个数</td>
</tr>
<tr>
<td>$*</td>
<td>以一个单字符串显示所有向脚本传递的参数</td>
</tr>
<tr>
<td>$$</td>
<td>脚本运行的当前进程ID号</td>
</tr>
<tr>
<td>$!</td>
<td>后台运行的最后一个进程的ID号</td>
</tr>
<tr>
<td>$@</td>
<td>与$*相同，但是使用时加引号，并在引号中返回每个参数。</td>
</tr>
<tr>
<td>$-</td>
<td>显示Shell使用的当前选项，与set命令功能相同。</td>
</tr>
<tr>
<td>$?</td>
<td>显示最后命令的退出状态。0表示没有错误，其他任何值表明有错误。</td>
</tr>
</tbody>
</table>
<h3 id="流和重定向"><a href="#流和重定向" class="headerlink" title="流和重定向"></a>流和重定向</h3><p>Bash有很强大的工具来处理程序之间的协同工作。使用流，我们能将一个程序的输出发送到另一个程序或文件，因此，我们能方便地记录日志或做一些其它我们想做的事。</p>
<p>管道给了我们创建传送带的机会，控制程序的执行成为可能。</p>
<p>学习如何使用这些强大的、高级的工具是非常非常重要的。</p>
<h4 id="输入、输出流"><a href="#输入、输出流" class="headerlink" title="输入、输出流"></a>输入、输出流</h4><p>Bash接收输入，并以字符序列或 <strong>字符流</strong> 的形式产生输出。这些流能被重定向到文件或另一个流中。</p>
<p>有三个文件描述符：</p>
<table>
<thead>
<tr>
<th>代码</th>
<th>描述符</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>0</code></td>
<td><code>stdin</code></td>
<td>标准输入</td>
</tr>
<tr>
<td><code>1</code></td>
<td><code>stdout</code></td>
<td>标准输出</td>
</tr>
<tr>
<td><code>2</code></td>
<td><code>stderr</code></td>
<td>标准错误输出</td>
</tr>
</tbody>
</table>
<h4 id="重定向"><a href="#重定向" class="headerlink" title="重定向"></a>重定向</h4><p>重定向让我们可以控制一个命令的输入来自哪里，输出结果到什么地方。这些运算符在控制流的重定向时会被用到：</p>
<table>
<thead>
<tr>
<th>Operator</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>&gt;</code></td>
<td>重定向输出</td>
</tr>
<tr>
<td><code>&amp;&gt;</code></td>
<td>重定向输出和错误输出</td>
</tr>
<tr>
<td><code>&amp;&gt;&gt;</code></td>
<td>以附加的形式重定向输出和错误输出</td>
</tr>
<tr>
<td><code>&lt;</code></td>
<td>重定向输入</td>
</tr>
<tr>
<td><code>&lt;&lt;</code></td>
<td><a href="http://tldp.org/LDP/abs/html/here-docs.html" target="_blank" rel="noopener">Here文档</a> 语法</td>
</tr>
<tr>
<td><code>&lt;&lt;&lt;</code></td>
<td><a href="http://www.tldp.org/LDP/abs/html/x17837.html" target="_blank" rel="noopener">Here字符串</a></td>
</tr>
</tbody>
</table>
<p>以下是一些使用重定向的例子：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">### ls的结果将会被写到list.txt中</span></span><br><span class="line">ls -l &gt; list.txt</span><br><span class="line"></span><br><span class="line"><span class="comment">### 将输出附加到list.txt中</span></span><br><span class="line">ls -a &gt;&gt; list.txt</span><br><span class="line"></span><br><span class="line"><span class="comment">### 所有的错误信息会被写到errors.txt中</span></span><br><span class="line">grep da * 2&gt; errors.txt</span><br><span class="line"></span><br><span class="line"><span class="comment">### 从errors.txt中读取输入</span></span><br><span class="line">less &lt; errors.txt</span><br></pre></td></tr></table></figure>
<h4 id="dev-null-文件"><a href="#dev-null-文件" class="headerlink" title="/dev/null 文件"></a><code>/dev/null</code> 文件</h4><p>如果希望执行某个命令，但又不希望在屏幕上显示输出结果，那么可以将输出重定向到 /dev/null：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ command &gt; /dev/null</span><br></pre></td></tr></table></figure>
<p>/dev/null 是一个特殊的文件，写入到它的内容都会被丢弃；如果尝试从该文件读取内容，那么什么也读不到。但是 /dev/null 文件非常有用，将命令的输出重定向到它，会起到”禁止输出”的效果。</p>
<p>如果希望屏蔽 stdout 和 stderr，可以这样写：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ command &gt; /dev/null 2&gt;&amp;1</span><br></pre></td></tr></table></figure>
<h3 id="Debugging"><a href="#Debugging" class="headerlink" title="Debugging"></a>Debugging</h3><p>shell提供了用于debugging脚本的工具。如果我们想以debug模式运行某脚本，可以在其shebang中使用一个特殊的选项：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">#!/bin/bash options</span><br></pre></td></tr></table></figure>
<p>options是一些可以改变shell行为的选项。下表是一些可能对你有用的选项：</p>
<table>
<thead>
<tr>
<th>Short</th>
<th>Name</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>-f</code></td>
<td>noglob</td>
<td>禁止文件名展开（globbing）</td>
</tr>
<tr>
<td><code>-i</code></td>
<td>interactive</td>
<td>让脚本以 <em>交互</em> 模式运行</td>
</tr>
<tr>
<td><code>-n</code></td>
<td>noexec</td>
<td>读取命令，但不执行（语法检查）</td>
</tr>
<tr>
<td><code>-t</code></td>
<td>—</td>
<td>执行完第一条命令后退出</td>
</tr>
<tr>
<td><code>-v</code></td>
<td>verbose</td>
<td>在执行每条命令前，向<code>stderr</code>输出该命令</td>
</tr>
<tr>
<td><code>-x</code></td>
<td>xtrace</td>
<td>在执行每条命令前，向<code>stderr</code>输出该命令以及该命令的扩展参数</td>
</tr>
</tbody>
</table>
<p>举个例子，如果我们在脚本中指定了<code>-x</code>例如：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">#!/bin/bash -x</span><br><span class="line"></span><br><span class="line">for (( i = 0; i &lt; 3; i++ )); do</span><br><span class="line">  echo $i</span><br><span class="line">done</span><br></pre></td></tr></table></figure>
<p>这会向<code>stdout</code>打印出变量的值和一些其它有用的信息：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">$ ./my_script</span><br><span class="line">+ (( i = 0 ))</span><br><span class="line">+ (( i &lt; 3 ))</span><br><span class="line">+ <span class="built_in">echo</span> 0</span><br><span class="line">0</span><br><span class="line">+ (( i++  ))</span><br><span class="line">+ (( i &lt; 3 ))</span><br><span class="line">+ <span class="built_in">echo</span> 1</span><br><span class="line">1</span><br><span class="line">+ (( i++  ))</span><br><span class="line">+ (( i &lt; 3 ))</span><br><span class="line">+ <span class="built_in">echo</span> 2</span><br><span class="line">2</span><br><span class="line">+ (( i++  ))</span><br><span class="line">+ (( i &lt; 3 ))</span><br></pre></td></tr></table></figure>
<p>有时我们需要debug脚本的一部分。这种情况下，使用<code>set</code>命令会很方便。这个命令可以启用或禁用选项。使用<code>-</code>启用选项，<code>+</code>禁用选项：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#!/bin/bash</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">echo</span> <span class="string">"xtrace is turned off"</span></span><br><span class="line"><span class="built_in">set</span> -x</span><br><span class="line"><span class="built_in">echo</span> <span class="string">"xtrace is enabled"</span></span><br><span class="line"><span class="built_in">set</span> +x</span><br><span class="line"><span class="built_in">echo</span> <span class="string">"xtrace is turned off again"</span></span><br></pre></td></tr></table></figure>
<h3 id="资料"><a href="#资料" class="headerlink" title="资料"></a>资料</h3><ul>
<li><a href="https://github.com/alebcay/awesome-shell" target="_blank" rel="noopener">awesome-shell</a>，shell 资源列表</li>
<li><a href="https://github.com/awesome-lists/awesome-bash" target="_blank" rel="noopener">awesome-bash</a>，bash 资源列表</li>
<li><a href="https://github.com/denysdovhan/bash-handbook" target="_blank" rel="noopener">bash-handbook</a></li>
<li><a href="https://github.com/vuuihc/bash-guide" target="_blank" rel="noopener">bash-guide</a> ，bash 基本用法指南</li>
<li><a href="https://github.com/Bash-it/bash-it" target="_blank" rel="noopener">bash-it</a>，为你日常使用，开发以及维护 shell 脚本和自定义命令提供了一个可靠的框架</li>
<li><a href="http://dotfiles.github.io/" target="_blank" rel="noopener">dotfiles.github.io</a>，上面有bash和其它shell的各种dotfiles集合以及shell框架的链接</li>
<li><a href="http://www.runoob.com/linux/linux-shell.html" target="_blank" rel="noopener">Runoob Shell 教程</a></li>
</ul>
<p>最后，Stack Overflow上 <a href="https://stackoverflow.com/questions/tagged/bash" target="_blank" rel="noopener">bash 标签下</a>有很多你可以学习的问题，当你遇到问题时，也是一个提问的好地方。</p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        
  <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
    <div>如果文章对您有帮助，请随意打赏</div>
    <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
      <span>赏</span>
    </button>
    <div id="QR" style="display: none;">
      
        <div id="wechat" style="display: inline-block">
          <img id="wechat_qr" src="https://i.loli.net/2018/10/15/5bc436827b4bc.png" alt="刘韬 WeChat Pay"/>
          <p>微信打赏</p>
        </div>
      
      
        <div id="alipay" style="display: inline-block">
          <img id="alipay_qr" src="https://i.loli.net/2018/10/15/5bc4368266e2b.png" alt="刘韬 Alipay"/>
          <p>支付宝打赏</p>
        </div>
      
    </div>
  </div>


      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/linux/" rel="tag"># linux</a>
          
            <a href="/tags/shell/" rel="tag"># shell</a>
          
            <a href="/tags/bash/" rel="tag"># bash</a>
          
        </div>
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/11/13/openstackauth/" rel="next" title="django_openstack_auth认证与集成方法">
                <i class="fa fa-chevron-left"></i> django_openstack_auth认证与集成方法
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/12/04/vim/" rel="prev" title="Vim 学习笔记">
                Vim 学习笔记 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/uploads/avatar.png"
               alt="刘韬" />
          <p class="site-author-name" itemprop="name">刘韬</p>
           
              <p class="site-description motion-element" itemprop="description"></p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">26</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">10</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">12</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/kusole" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://www.douban.com/people/83381421/" target="_blank" title="豆瓣">
                  
                    <i class="fa fa-fw fa-twitter"></i>
                  
                  豆瓣
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://www.zhihu.com/people/liu-tao-86-26-47/activities" target="_blank" title="知乎">
                  
                    <i class="fa fa-fw fa-facebook"></i>
                  
                  知乎
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://weibo.com/6193724399/profile?topnav=1&wvr=6&is_all=1" target="_blank" title="微博">
                  
                    <i class="fa fa-fw fa-weibo"></i>
                  
                  微博
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#Shell-快速指南"><span class="nav-number">1.</span> <span class="nav-text">Shell 快速指南</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#概述"><span class="nav-number">1.1.</span> <span class="nav-text">概述</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#什么是-shell"><span class="nav-number">1.1.1.</span> <span class="nav-text">什么是 shell</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#什么是-shell-脚本"><span class="nav-number">1.1.2.</span> <span class="nav-text">什么是 shell 脚本</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Shell-环境"><span class="nav-number">1.1.3.</span> <span class="nav-text">Shell 环境</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#指定脚本解释器"><span class="nav-number">1.1.3.1.</span> <span class="nav-text">指定脚本解释器</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#模式"><span class="nav-number">1.1.4.</span> <span class="nav-text">模式</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#交互模式"><span class="nav-number">1.1.4.1.</span> <span class="nav-text">交互模式</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#非交互模式"><span class="nav-number">1.1.4.2.</span> <span class="nav-text">非交互模式</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Shell-编程"><span class="nav-number">1.2.</span> <span class="nav-text">Shell 编程</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#解释器"><span class="nav-number">1.2.1.</span> <span class="nav-text">解释器</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#注释"><span class="nav-number">1.2.2.</span> <span class="nav-text">注释</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#变量"><span class="nav-number">1.2.3.</span> <span class="nav-text">变量</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#局部变量"><span class="nav-number">1.2.3.1.</span> <span class="nav-text">局部变量</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#环境变量"><span class="nav-number">1.2.3.2.</span> <span class="nav-text">环境变量</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#位置参数"><span class="nav-number">1.2.3.3.</span> <span class="nav-text">位置参数</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Shell扩展"><span class="nav-number">1.2.4.</span> <span class="nav-text">Shell扩展</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#大括号扩展"><span class="nav-number">1.2.4.1.</span> <span class="nav-text">大括号扩展</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#命令置换"><span class="nav-number">1.2.4.2.</span> <span class="nav-text">命令置换</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#算数扩展"><span class="nav-number">1.2.4.3.</span> <span class="nav-text">算数扩展</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#单引号和双引号"><span class="nav-number">1.2.4.4.</span> <span class="nav-text">单引号和双引号</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#数组"><span class="nav-number">1.2.5.</span> <span class="nav-text">数组</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#创建数组"><span class="nav-number">1.2.5.1.</span> <span class="nav-text">创建数组</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#获取数组元素"><span class="nav-number">1.2.5.2.</span> <span class="nav-text">获取数组元素</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#获取数组长度"><span class="nav-number">1.2.5.3.</span> <span class="nav-text">获取数组长度</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#向数组中添加元素"><span class="nav-number">1.2.5.4.</span> <span class="nav-text">向数组中添加元素</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#从数组中删除元素"><span class="nav-number">1.2.5.5.</span> <span class="nav-text">从数组中删除元素</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#运算符"><span class="nav-number">1.2.6.</span> <span class="nav-text">运算符</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#算术运算符"><span class="nav-number">1.2.6.1.</span> <span class="nav-text">算术运算符</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#关系运算符"><span class="nav-number">1.2.6.2.</span> <span class="nav-text">关系运算符</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#布尔运算符"><span class="nav-number">1.2.6.3.</span> <span class="nav-text">布尔运算符</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#逻辑运算符"><span class="nav-number">1.2.6.4.</span> <span class="nav-text">逻辑运算符</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#字符串运算符"><span class="nav-number">1.2.6.5.</span> <span class="nav-text">字符串运算符</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#文件测试运算符"><span class="nav-number">1.2.6.6.</span> <span class="nav-text">文件测试运算符</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#语句"><span class="nav-number">1.2.7.</span> <span class="nav-text">语句</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#条件语句"><span class="nav-number">1.2.7.1.</span> <span class="nav-text">条件语句</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#基元和组合表达式"><span class="nav-number">1.2.7.1.1.</span> <span class="nav-text">基元和组合表达式</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#使用if"><span class="nav-number">1.2.7.1.2.</span> <span class="nav-text">使用if</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#使用case"><span class="nav-number">1.2.7.1.3.</span> <span class="nav-text">使用case</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#循环语句"><span class="nav-number">1.2.7.2.</span> <span class="nav-text">循环语句</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#for循环"><span class="nav-number">1.2.7.2.1.</span> <span class="nav-text">for循环</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#while循环"><span class="nav-number">1.2.7.2.2.</span> <span class="nav-text">while循环</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#until循环"><span class="nav-number">1.2.7.2.3.</span> <span class="nav-text">until循环</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#select循环"><span class="nav-number">1.2.7.2.4.</span> <span class="nav-text">select循环</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#break-和-continue"><span class="nav-number">1.2.7.2.5.</span> <span class="nav-text">break 和 continue</span></a></li></ol></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#函数"><span class="nav-number">1.2.8.</span> <span class="nav-text">函数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#流和重定向"><span class="nav-number">1.2.9.</span> <span class="nav-text">流和重定向</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#输入、输出流"><span class="nav-number">1.2.9.1.</span> <span class="nav-text">输入、输出流</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#重定向"><span class="nav-number">1.2.9.2.</span> <span class="nav-text">重定向</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#dev-null-文件"><span class="nav-number">1.2.9.3.</span> <span class="nav-text">/dev/null 文件</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Debugging"><span class="nav-number">1.2.10.</span> <span class="nav-text">Debugging</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#资料"><span class="nav-number">1.2.11.</span> <span class="nav-text">资料</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2016 - 
  <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">刘韬</span>

</div>


<div class="Hosted-by">
  由 <a class="theme-link" href="https://pages.github.com/">GitHub Pages</a> 强力驱动
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>

<!-- <div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>

-->


        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  

  
</div>


        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  






  
  <script type="text/javascript" src="//cdn.jsdelivr.net/jquery/2.1.3/jquery.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/fastclick/1.0.6/fastclick.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/jquery.lazyload/1.9.3/jquery.lazyload.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/velocity/1.2.3/velocity.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/velocity/1.2.3/velocity.ui.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/fancybox/2.1.5/jquery.fancybox.pack.js"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  


  




	





  





  





  






  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length == 0) {
      search_path = "search.xml";
    }
    var path = "/" + search_path;
    // monitor main search box;

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.popup').toggle();
    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';
      $.ajax({
        url: path,
        dataType: "xml",
        async: true,
        success: function( xmlResponse ) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = $( "entry", xmlResponse ).map(function() {
            return {
              title: $( "title", this ).text(),
              content: $("content",this).text(),
              url: $( "url" , this).text()
            };
          }).get();
          var $input = document.getElementById(search_id);
          var $resultContent = document.getElementById(content_id);
          $input.addEventListener('input', function(){
            var matchcounts = 0;
            var str='<ul class=\"search-result-list\">';
            var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
            $resultContent.innerHTML = "";
            if (this.value.trim().length > 1) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var content_index = [];
                var data_title = data.title.trim().toLowerCase();
                var data_content = data.content.trim().replace(/<[^>]+>/g,"").toLowerCase();
                var data_url = decodeURIComponent(data.url);
                var index_title = -1;
                var index_content = -1;
                var first_occur = -1;
                // only match artiles with not empty titles and contents
                if(data_title != '') {
                  keywords.forEach(function(keyword, i) {
                    index_title = data_title.indexOf(keyword);
                    index_content = data_content.indexOf(keyword);
                    if( index_title >= 0 || index_content >= 0 ){
                      isMatch = true;
                      if (i == 0) {
                        first_occur = index_content;
                      }
                    }

                  });
                }
                // show search results
                if (isMatch) {
                  matchcounts += 1;
                  str += "<li><a href='"+ data_url +"' class='search-result-title'>"+ data_title +"</a>";
                  var content = data.content.trim().replace(/<[^>]+>/g,"");
                  if (first_occur >= 0) {
                    // cut out 100 characters
                    var start = first_occur - 20;
                    var end = first_occur + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if(start == 0){
                      end = 50;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    var match_content = content.substring(start, end);
                    // highlight all keywords
                    keywords.forEach(function(keyword){
                      var regS = new RegExp(keyword, "gi");
                      match_content = match_content.replace(regS, "<b class=\"search-keyword\">"+keyword+"</b>");
                    });

                    str += "<p class=\"search-result\">" + match_content +"...</p>"
                  }
                  str += "</li>";
                }
              })};
            str += "</ul>";
            if (matchcounts == 0) { str = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>' }
            if (keywords == "") { str = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>' }
            $resultContent.innerHTML = str;
          });
          proceedsearch();
        }
      });}

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched == false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(function(e){
      $('.popup').hide();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    });
    $('.popup').click(function(e){
      e.stopPropagation();
    });
  </script>





  

  

  
  


  

</body>
</html>
